#include <QCoreApplication>
#include <iostream>


#include <sched.h>
#include<stdio.h>
#include <sys/mman.h>

#include <native/task.h>
#include <native/timer.h>
#include <rtdk.h>

#include "measuretime.h"

using namespace std;


#define NSEC_PER_SEC    1000000000 /* The number of nsecs per sec. */

#define MY_PRIORITY    99

void upPriority(int priority)
{
    struct sched_param param;
    param.__sched_priority = priority;
    if(sched_setscheduler(0,SCHED_FIFO,&param) == -1)
    {
        perror("sched_setscheduler failed");
    }

    if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1)
    {
        perror("mlockall failed");
    }
}


void realTimeSleep(long long microsecond)
{
    struct timespec t;

    clock_gettime(CLOCK_REALTIME,&t);

    t.tv_nsec += microsecond*1000;

    while(t.tv_nsec >= NSEC_PER_SEC)
    {
        t.tv_nsec -= NSEC_PER_SEC;
        ++t.tv_sec;
    }
//    //qDebug()<<"before sleep- ***"<<"sec&****"<<t.tv_sec<<"nsec&&&&&&&&"<<t.tv_nsec<<endl;
    clock_nanosleep(CLOCK_REALTIME,TIMER_ABSTIME,&t,NULL);
}

int main(int argc,char **argv)
{
    QCoreApplication a(argc,argv);

    upPriority(99);

    struct sched_param param;

    param.__sched_priority = 99;
    sched_setscheduler(0,SCHED_FIFO,&param);
    //this->setStackSize(81920);
    int policy, priority;
    pthread_getschedparam(pthread_self(), &policy, (struct sched_param *)&priority);

    MeasureTime measure("hualei time test!",1,5,1000);

    while(1)
    {

        realTimeSleep(1000);
        measure.recordPeirodTime();

    }

    while(1)
    {
//        measure.recordInTime();
//         realTimeSleep(1000);
//         measure.recordOutTime();

    }


//    struct timespec t1,t2;

//    long time;

//    long tmax=0;
//    while(1)
//    {
//        clock_gettime(CLOCK_REALTIME, &t1);
//        realTimeSleep(1000);
//        clock_gettime(CLOCK_REALTIME, &t2);

//        time=t2.tv_nsec-t1.tv_nsec;

//        if(t2.tv_nsec<t1.tv_nsec)
//        {
//            time=t2.tv_nsec+NSEC_PER_SEC-t1.tv_nsec;
//        }

//        tmax=max(tmax,time);

////        cout << "=t="<<time/1000<<"-max--"<<tmax/1000<<endl;
//        rt_printf("Time: %ld.%06ld us,****max time:%lf us\n",
//               time / 1000,
//               time % 1000,
//               tmax/1000.0);
//    }

    a.exec();

    return 0;

}
